﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;

namespace NetSurveillance.WebApp.Exts
{
    public static class EnumExtension
    {
        public static IEnumerable<T> GetAllItems<T>(this Enum value)
        {
            return from object item in Enum.GetValues(typeof(T)) select (T)item;
        }

        public static IEnumerable<T> GetAllItems<T>() where T : struct
        {
            return Enum.GetValues(typeof(T)).Cast<T>();
        }

        public static IEnumerable<T> GetAllSelectedItems<T>(this Enum value)
        {
            int valueAsInt = Convert.ToInt32(value, CultureInfo.InvariantCulture);

            return from object item in Enum.GetValues(typeof (T))
                   let itemAsInt = Convert.ToInt32(item, CultureInfo.InvariantCulture)
                   where itemAsInt == (valueAsInt & itemAsInt)
                   select (T) item;
        }

        public static bool Contains<T>(this Enum value, T request)
        {
            int valueAsInt = Convert.ToInt32(value, CultureInfo.InvariantCulture);
            int requestAsInt = Convert.ToInt32(request, CultureInfo.InvariantCulture);

            return requestAsInt == (valueAsInt & requestAsInt);
        }
    }
}